package com.mantou.scucorse.core.scheduler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.mantou.scucorse.core.entity.ScuCourse;
import com.mantou.scucorse.core.entity.Task;
import com.mantou.scucorse.core.service.ScuCourseService;
import com.mantou.scucorse.core.service.TaskService;
import com.mantou.scucorse.utils.SystemInfo;
import com.mantou.scucorse.utils.TaskStatus;

public class TasksExecuter implements Runnable {

	@Autowired
	private ScuCourseService scuCourseService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private CourseNetInvoker courseNetInvoker;
	
	private ThreadPoolTaskExecutor executor;
	
	
	public ThreadPoolTaskExecutor getExecutor() {
		return executor;
	}

	public void setExecutor(ThreadPoolTaskExecutor executor) {
		this.executor = executor;
	}

	public void run() {
		// TODO Auto-generated method stub

		if(SystemInfo.taskHibrate){
			return;
		}
		List<Task> tasks = taskService.findAvaible();
		for(Task task:tasks){
			executor.execute(new TaskExecuter(task,scuCourseService,taskService));
		}
		
		List<ScuCourse> scuCourses = scuCourseService.findAvailable();
		for(ScuCourse scuCourse:scuCourses){
			executor.execute(new CourseInfoUpdater(scuCourse));
		}
	}
	private class CourseInfoUpdater implements Runnable{

		private ScuCourse scuCourse;
		
		public CourseInfoUpdater(ScuCourse scuCourse) {
			super();
			this.scuCourse = scuCourse;
		}

		public void run() {
			// TODO Auto-generated method stub
			courseNetInvoker.updateCourseInfo(scuCourse.getId());
		}
		
	}
	
	private class TaskExecuter implements Runnable {

		
		private Task task;
		
		private ScuCourse scuCourse;
		
		private ScuCourseService scuCourseService;
		
		private TaskService taskService;
		
		public TaskExecuter(Task task,ScuCourseService scuCourseService,TaskService taskService) {
			super();
			this.task = task;
			this.scuCourseService = scuCourseService;
			this.taskService = taskService;
		}

		public void run() {
			// TODO Auto-generated method stub
			scuCourse = scuCourseService.findByPrimaryKey(task.getCourseid());
			if(scuCourse.getLeftnumber() == null || scuCourse.getLeftnumber() <=0){
				scuCourse = courseNetInvoker.updateCourseInfo(scuCourse.getId());
			}
			if(scuCourse == null || scuCourse.getLeftnumber() <=0){
				return;
			}
			//now there is a course available in SCU jiaowuchu
			if(courseNetInvoker.selectCourse(task)){
				scuCourse.setLeftnumber(scuCourse.getLeftnumber() -1);
				scuCourseService.updateByPrimaryKey(scuCourse);
				
				task.setStatus(TaskStatus.COMPLETE.getStatus());
				taskService.updateByPrimaryKey(task);
			}
		}

	}
}
